<template>
  <div class="body-container layout-padding">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-tree ref="orgTreeRef" :data="state.treeData" node-key="id" :expand-on-click-node="false" default-expand-all  highlight-current @node-click="treeClick"></el-tree>
      </el-col>
      <el-col :span="20">
        <el-button size="default" type="primary" @click="addOrg">
          <el-icon><ele-CirclePlus /></el-icon>添加下级组织
        </el-button>
        <table class="mytable">
          <tbody>
            <tr>
              <th style="width: 15%">组织名称</th>
              <th>{{state.activeTreeNode.label}}</th>
              <th style="width: 15%">
                <el-button size="small" type="primary" @click="editOrg(state.activeTreeNode.id)">修改</el-button>
              </th>
            </tr>
          </tbody>
        </table>
      </el-col>
    </el-row>
    <el-dialog :title="state.popupTitle" v-model="state.entityDetailVisible" :close-on-click-modal="false" width="780px">
      <OrgDetail v-if="state.entityDetailVisible" v-model="state.entityDetailVisible" :entityId="state.popupEntityId" :pid="state.activeTreeNode.id"></OrgDetail>
    </el-dialog>
  </div>
</template>

<script setup name="orgIndex">
import request from '/@/utils/request';
import {reactive, ref, onMounted, onUnmounted, defineAsyncComponent, nextTick, defineProps} from "vue";
import mittBus from "/@/utils/mitt";
// 定义dom
const orgTreeRef = ref(null);
// 引入组件
const OrgDetail = defineAsyncComponent(() => import('/@/views/sys/org/orgDetail.vue'));

const state = reactive({
  treeData : [],
  activeTreeNode : {},

  entityDetailVisible : false,
  popupTitle : '',
  popupEntityId : 0,
})

const loadOrgTree = () =>{
  request({
    url: '/sys/org/orgtreedata',
    data: {orgId : 1}
  }).then(res => {
    const { data } = res
    state.treeData = data
    if(state.treeData.length > 0){
      state.activeTreeNode = state.treeData[0]
      nextTick(()=>{
        orgTreeRef.value.setCurrentKey("1")
      })
    }
  })
}
const treeClick = (treeNode)=>{
  state.activeTreeNode = treeNode
}
const addOrg = ()=>{
  state.popupEntityId = 0;
  state.popupTitle= "新增组织"
  state.entityDetailVisible= true
}
const editOrg = (id)=>{
  state.popupEntityId = id;
  state.popupTitle= "修改组织"
  state.entityDetailVisible= true
}
onMounted(()=>{
  loadOrgTree();
  mittBus.on("orgchange", ()=>{
    loadOrgTree();
  })
})
onUnmounted(()=>{
  mittBus.off("orgchange", ()=>{})
})
</script>

<style scoped lang="scss">

</style>
